package com.kuqi.controller;

import com.kuqi.config.Result;
import com.kuqi.domain.PageVo;
import com.kuqi.domain.User;
import com.kuqi.domain.Vo;
import com.kuqi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @author:kuqi
 * @createTime:2021/11/9 20:02
 * @description:
 */
@Slf4j
@RestController  //springboot注解，表示无需页面跳转返回前端json数据
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/save")
    private Result<?> save(@RequestBody User user){  //方法参数里的RequestBody表示前端传递的json转变成java中的实体类
        if (user.getPassword()==null){
            user.setPassword("123456");
        }
        userService.save(user);
        return Result.success();
    }

    @PutMapping("/update")
    private Result<?> updateUser(@RequestBody User user){
        userService.updateUser(user);
        return Result.success();
    }

    @DeleteMapping("/delete")
    private Result<?> deleteUserById(@RequestParam Integer id){
        userService.deleteUserById(id);
        return Result.success();
    }

    /**
     *
     * @return
     */
    @GetMapping("/userList")
    private Result<?> queryUserList(@RequestParam Integer pageNum,//@RequestParam是springMVC框架注解可用于请求参数与后台参数的不同的绑定，也可以用于参数的初始化
                                    @RequestParam Integer pageSize,
                                    @RequestParam(value = "search") String searchContent){
        PageVo pageVo = new PageVo();
        pageVo.setPageNum(pageNum);
        pageVo.setPageSize(pageSize);
        pageVo.setSearchContent(searchContent);

        Vo<User> userVo = userService.getUserListByPage(pageVo);

        return Result.success(userVo);
    }

    /**
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    private Result<?> login(HttpServletRequest request, @RequestBody User user){
        User result = userService.loginCheck(user);
        if (result == null){
            return Result.error("-1","账号或密码错误");
        }
        Result<User> success = Result.success(result);

        /*将id放到session域中*/
        HttpSession session = request.getSession();
        session.setAttribute("user",result);

        return success;  //登录成功，返回用户信息给前端
    }


    /**
     * @param user
     * @return
     */
    @PostMapping("/register")
    private Result<?> register(@RequestBody User user){
        userService.register(user);
        return Result.success();
    }

    @GetMapping("/getUser")
    private Result<?> getUser(Integer id){
        User result = userService.getUserById(id);
        return Result.success(result);
    }
}
